package gis.common;

import gis.core.utils.XMLUtils;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class ServiceFactory {

    private static Logger logger = LoggerFactory.getLogger(ServiceFactory.class);
    private static Map<String, String> classadapter = null;

    /**
     * @param t
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws ClassNotFoundException
     */
    @SuppressWarnings("unchecked")
    public static <T> T getInstance(Class<T> t) {
        T t1 = null;
        try {
            if (classadapter == null) {
                LoadClassAdapter();
            }

            // 获取接口名称
            String[] strings = t.getName().split("\\.");
            String name = strings[strings.length - 1];

            // 获取实例名称
            String nameString = "";
            if (classadapter.containsKey(name)) {
                nameString = t.getName().replaceAll("service", "serviceImpl").replace(name, classadapter.get(name));
            } else {
                nameString = t.getName().replaceAll("service", "serviceImpl") + "Impl";
            }

            t1 = (T) Class.forName(nameString).newInstance();
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.getStackTrace();
        }
        return t1;
    }

    /**
     * 读取配置文件
     */
    private static void LoadClassAdapter() {
        classadapter = new HashMap<String, String>();
        String area = GisConfig.GetInstance().getArea();
        Element element = XMLUtils.getInstance().loadXmlFileName("gisconfig/" + area + "/classadapter." + area + ".xml");
        NodeList list = element.getElementsByTagName("classadapter");

        if (list != null && list.getLength() > 0) {
            for (int i = 0; i < list.getLength(); i++) {
                Element node = (Element) list.item(i);
                if (node != null) {
                    String keyString = node.getAttribute("interface");
                    if (classadapter.containsKey(keyString) == false) {
                        classadapter.put(keyString, node.getAttribute("iclass"));
                    } else {
                        logger.info("读取类适配classadapter." + area + ".xml 时发现关键字在 " + keyString + " 重复，请确认！");
                    }
                }
            }
        }
    }
}
